import { defineStore } from 'pinia'
import { ref } from 'vue'
import store from '..'
import type { RouteRecordRaw, RouteLocationNormalized } from 'vue-router'
import { usePermissionStore } from './permission'
// import { useRouter } from 'vue-router'

// 递归查询子类中是否存在
function findChildren(routes: RouteRecordRaw[], path: string): RouteRecordRaw | undefined {
  for (const route of routes) {
    if (route.path === path) {
      return route
    }
    if (route.children) {
      const res = findChildren(route.children, path)
      if (res) {
        return res
      }
    }
  }
  return undefined
}

const tagsStore = defineStore('tags', () => {
  const tags = ref<RouteLocationNormalized[]>([])
  // * 当前激活的标签
  const activeTag = ref('')
  const store = usePermissionStore()

  function pushTag(tag: RouteLocationNormalized) {
    // todo 过滤路由 是否是异步加载后的路由
    const route = findChildren(store.asyncRoutes, tag.path)
    if (route) {
      // todo 如果不存在重复路由 则添加
      !tags.value.find(item => item.path === tag.path) && tags.value.push(tag)
    }
  }
  // todo 删除标签
  function removeTag(tag: RouteLocationNormalized) {
    const index = tags.value.findIndex(item => item.path === tag.path)
    if (index > -1) {
      tags.value.splice(index, 1)
    }
  }
  return { tags, activeTag, pushTag, removeTag }
})

export const useTagsStore = () => tagsStore(store)
